package webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.person;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllSoftware;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllSoftwaresImplToSoftwareLinkPanel;
import webEquipeRechercheGwt.client.entityMirror.SoftwareMirror;
import webEquipeRechercheGwt.client.entityShowingPanel.PersonPanel;
import webEquipeRechercheGwt.client.entityShowingPanel.linkCreationPanel.ToSoftwareLinkCreationPanel;
import webEquipeRechercheGwt.client.handler.creation.link.person.ClickHandlerPersonToSoftwareLink;
import webEquipeRechercheGwt.client.services.SoftwareService;
import webEquipeRechercheGwt.client.services.SoftwareServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class PersonToSoftwareLinkCreationPanel extends HorizontalPanel implements
		ToSoftwareLinkCreationPanel {

	private PersonPanel origine;
	private List<SoftwareMirror> softwares;
	private ListBox listBox;
	private Button validation;
	
	public PersonToSoftwareLinkCreationPanel(PersonPanel origine){
		super();
		this.origine = origine;
		softwares = new ArrayList<SoftwareMirror>();
		listBox = new ListBox();
		listBox.setVisibleItemCount(1);
		validation = new Button("Create link");
		validation.addClickHandler(new ClickHandlerPersonToSoftwareLink(softwares, listBox, origine.getMirror(), origine.getMainPanel()));
	}
	
	private void loadAllPersons(){
		SoftwareServiceAsync service = GWT.create(SoftwareService.class);
		AsyncCallback<Collection<SoftwareMirror>> callback = new CallBackGetAllSoftware(new CommandGetAllSoftwaresImplToSoftwareLinkPanel(this));
		service.getSoftwares(callback);
	}
	
	public void setSoftwares(Collection<SoftwareMirror> result){
		softwares.clear();
		softwares.addAll(result);
		softwares.removeAll(origine.getMirror().getSoftwares());
		updateSelection();
	}
	
	private void updateSelection(){
		listBox.clear();
		for(SoftwareMirror p : softwares){
			listBox.addItem(p.getTitle());
		}
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		add(listBox);
		add(validation);
		loadAllPersons();
	}

}
